package com.demo.miaosha.Service;


import com.alibaba.fastjson.JSON;
import net.sf.jsqlparser.expression.CastExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;

/**
 * RedisService
 *
 * @blame 吴经纶
 */
@Service
public class RedisService {

    @Resource
    private JedisPool jp;

    public <T> T get(String key,Class<T> clazz){
        Jedis jedis = jp.getResource();
        String value = jedis.get(key);
        String obz = stringToObject(value,String.class);
        return (T)obz;
    }
    public <T>void set (String key,T value){
        Jedis jedis = jp.getResource();
        jedis.set(key,objectToString(value));
    }
    private <T>T stringToObject(String value,Class<T> clazz)throws ClassCastException {
        if (clazz == Integer.class ) {
            return (T)Integer.valueOf(value);
        } else if (clazz == Long.class){
            return (T)Long.valueOf(value);
        } else if (String.class == clazz) {
            return (T)value;
        }else {
            return JSON.parseObject(value,clazz);
        }
    }

    private <T> String objectToString(T value){
        if (value == null){
            return null;
        }
        Class<?> clazz = value.getClass();
        if (clazz == Integer.class || clazz == Long.class) {
            return ""+value;
        } else if (String.class == clazz) {
            return (String)value;
        }else {
            return JSON.toJSONString(value);
        }
    }
}
